from typing import Dict, Annotated, Any
from fastapi import APIRouter, Body, Request, HTTPException
from starlette.responses import StreamingResponse, JSONResponse

from server.openai_server import create_server, clear_session_history
from common.comm_utils import response_with_graph_agent_history

router = APIRouter(prefix="/ai", tags=["AI接口"])
server_instance = create_server()

@router.post("/query", summary="答问接口")
async def query(json_post: Annotated[Dict[str, Any], Body()], req: Request):
    data = json_post
    user_id = data.get('user_id', '周佳乐')
    message = data.get('message', '')
    return StreamingResponse(response_with_graph_agent_history(user_id, message), media_type="text/event-stream")

@router.post("/clear_chat_history", summary="清理聊天记录缓存接口")
async def clear_history(json_post: Annotated[Dict[str, Any], Body()], req: Request):
    data = json_post
    session_id = data.get('session_id', 'LuckyZhou')
    clear_session_history(session_id)
    return JSONResponse(status_code=200, content="OK")

@router.post("/handle_delete_entry", summary="删除知识库条目")
async def handle_delete_entry(json_post: Annotated[Dict[str, Any], Body()], req: Request):
    data = json_post
    entry_id = data.get('entry_id', '')
    if not entry_id:
        return JSONResponse(status_code=400, content={'status': 'error', 'message': 'Entry ID is required.'})
    status = server_instance.knowledge_base.delete_entry(entry_id)
    if status:
        return JSONResponse(content={'status': 'success', 'message': 'Entry deleted successfully.'})
    return JSONResponse(status_code=500, content={'status': 'error', 'message': 'Failed to delete entry.'}) 